from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db.models import Q

from app01.utils import encrypt
from app01 import models
from django import forms


class RegisterModelForm(forms.ModelForm):
    password = forms.CharField(label='密码',
                               min_length=8,
                               max_length=32,
                               error_messages={
                                   'min_length': '密码长度不能小于8个字符',
                                   'max_length': '密码长度不能大于32个字符'
                               },
                               widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='确认密码',
                                       min_length=8,
                                       max_length=32,
                                       error_messages={
                                           'min_length': '重复密码长度不能小于8个字符',
                                           'max_length': '重复密码长度不能大于32个字符'
                                       }, widget=forms.PasswordInput())
    email = forms.EmailField(label='邮箱', widget=forms.EmailInput())
    # code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)

    # 钩子方法校验 -- 用户名
    # 1. 不能重复
    def clean_username(self):
        username = self.cleaned_data['username']
        # 表单类型时login的话，那么不用校验用户名是否存在
        # print(self.request.POST)
        # if self.request.POST.get('form-type') == 'login':
        #     return username

        # 否则走注册流程
        is_exists = models.UserInfo.objects.filter(username=username).exists()
        if is_exists:
            # self.add_error('username', '') 推荐raise方式，会自动调用ValidationError
            raise ValidationError('用户名已存在')
        return username

    def clean_password(self):
        pwd = self.cleaned_data['password']
        encrypt_pwd = encrypt.encrypt_md5(pwd)
        return encrypt_pwd

    # 钩子方法校验 -- 确认密码是不是一致
    def clean_confirm_password(self):
        # 校验的顺序，只能获取fields = ['username', 'email', 'password', 'confirm_password', 'phone_number']中
        # confirm_password前面字段的内容
        pwd = self.cleaned_data['password']
        confirm = self.cleaned_data['confirm_password']
        encrypt_confirm = encrypt.encrypt_md5(confirm)
        if pwd != encrypt_confirm:
            raise ValidationError('密码不一致')
        return confirm


class SendMessageForm(forms.Form):
    phone_number = forms.CharField(label='手机号', widget=forms.TextInput())

    def clean_phone_number(self):
        '''钩子方法校验'''
        phone_number = self.cleaned_data.get('phone_number')
        if not phone_number:
            raise ValidationError('密码错误')

        is_exists = models.UserInfo.objects.filter(phone_number=phone_number).exists()
        if is_exists:
            raise ValidationError('手机号已存在')

        return phone_number


class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', )
    password = forms.CharField(label='密码', widget=forms.PasswordInput(render_value=True))
    # confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        exists = models.UserInfo.objects.filter(Q(username=username)|Q(email=username)).exists()
        if not exists:
            raise ValidationError('用户名不存在')
        # 视图再取username的时候，实际取的是user_object
        return username

    def clean_password(self):
        pwd = self.cleaned_data['password']
        encrypt_pwd = encrypt.encrypt_md5(pwd)
        return encrypt_pwd

    # 钩子方法校验 -- 确认密码是不是一致
    # def clean_confirm_password(self):
    #     # 校验的顺序，只能获取fields = ['username', 'email', 'password', 'confirm_password', 'phone_number']中
    #     # confirm_password前面字段的内容
    #     pwd = self.cleaned_data['password']
    #     confirm = self.cleaned_data['confirm_password']
    #     encrypt_confirm = encrypt.encrypt_md5(confirm)
    #     if pwd != encrypt_confirm:
    #         raise ValidationError('密码不一致')
    #     return confirm
